package com.hoperun.nocserver.modules.user.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hoperun.nocserver.common.entity.Encrypt;
import com.hoperun.nocserver.common.entity.Request;
import com.hoperun.nocserver.common.entity.Response;
import com.hoperun.nocserver.common.utils.JsonUtil;
import com.hoperun.nocserver.common.utils.Md5Util;
import com.hoperun.nocserver.modules.base.service.BaseService;
import com.hoperun.nocserver.modules.user.constant.UserConst;
import com.hoperun.nocserver.modules.user.dao.SysUserMapper;
import com.hoperun.nocserver.modules.user.entity.SysUser;

@Component
public class SysUserService extends BaseService {

	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private Encrypt encrypt;

	public Response login(Request request) {
		Response response = new Response();
		SysUser loginUser = JsonUtil.toBean(request.getParameter(), SysUser.class);
		SysUser dbUser = sysUserMapper.login(loginUser.getUserId());
		if (dbUser == null) {
			// username does not exist
			response.setStatus(UserConst.USER_HAS_NO_PERMISSION);
			response.setMessage(UserConst.USER_DOES_NOT_EXIST);
		} else {

			if (dbUser.getPassword()
					.equals(Md5Util.md5(loginUser.getPassword(), encrypt.getUserPwdSalt(), encrypt.getUserPwdHash()))) {
				// login success
				// find roleinfo by user

			} else {
				// login fail Incorrect password
				response.setStatus(UserConst.USER_HAS_NO_PERMISSION);
				response.setMessage(UserConst.USER_INCORRECT_PASSWORD);
			}
		}
		return response;
	}

	public SysUser selectByPrimaryKey(String id) {
		return sysUserMapper.selectByPrimaryKey(id);
	}

	public List<SysUser> findAll() {
		return sysUserMapper.findAll();
	}

}
